<?php


namespace app\api\controller\v23;


use app\api\controller\v2\Auth;
use app\common\cachemodel\CouponCode;
use app\common\cachemodel\ZlCouponActive;
use app\common\lib\Util;
use think\Exception;
use think\exception\PDOException;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**
 * 春节活动
 * Class YearActiv
 * @package app\api\controller\v23
 */
class YearActiv extends Auth
{
    private $activeConfig = [
        2021 => [
            'active' => [ // 折扣优惠券【实现方式：优惠券活动领取】  $dt=>优惠券活动ID
                11 => 15,
                12 => 16,
                13 => 17,
                14 => 18,
                15 => 19,
                16 => 20,
                17 => 21,
            ],
            'code' => [ // 免费券领取【实现方式：优惠券兑换码领取】  每人限领一张
                11 => [ // 2021-02-11
                    'date' => 1613059200,       // 活动开始时间戳 2021-02-12 00:00:00
                    'end_date' => 1613066400,   // 活动结束时间戳 2021-02-12 02:00:00
                    'group_id' => 35  // 兑换码组号
                ],
                12 => [ // 2021-02-12
                    'date' => 1613102400,       // 活动开始时间戳 2021-02-12 12:00:00
                    'end_date' => 1613145600,   // 活动结束时间戳 2021-02-13 00:00:00
                    'group_id' => 36  // 兑换码组号
                ],
                13 => [ // 2021-02-13
                    'date' => 1613188800,       // 活动开始时间戳 2021-02-13 12:00:00
                    'end_date' => 1613232000,   // 活动结束时间戳 2021-02-14 00:00:00
                    'group_id' => 37  // 兑换码组号
                ],
                14 => [ // 2021-02-14
                    'date' => 1613275200,       // 活动开始时间戳 2021-02-14 12:00:00
                    'end_date' => 1613318400,   // 活动结束时间戳 2021-02-15 00:00:00
                    'group_id' => 38  // 兑换码组号
                ],
                15 => [ // 2021-02-15
                    'date' => 1613361600,       // 活动开始时间戳 2021-02-15 12:00:00
                    'end_date' => 1613404800,   // 活动结束时间戳 2021-02-16 00:00:00
                    'group_id' => 41  // 兑换码组号
                ],
                16 => [ // 2021-02-16
                    'date' => 1613448000,       // 活动开始时间戳 2021-02-16 12:00:00
                    'end_date' => 1613491200,   // 活动结束时间戳 2021-02-17 00:00:00
                    'group_id' => 40  // 兑换码组号
                ],
                17 => [ // 2021-02-17
                    'date' => 1613534400,       // 活动开始时间戳 2021-02-17 12:00:00
                    'end_date' => 1613577600,   // 活动结束时间戳 2021-02-18 00:00:00
                    'group_id' => 39  // 兑换码组号
                ],
            ]
        ]
    ];


    /**
     * 春节活动领取优惠券
     * param $dt int
     * $dt=>11    2021-02-11   一生报告 20张
     * $dt=>12    2021-02-12   年度运势 25张
     * $dt=>13    2021-02-13   单月运势 30张
     * $dt=>14    2021-02-14   合盘报告 30张
     * $dt=>15    2021-02-15   日运全年 35张
     * $dt=>16    2021-02-16   幸运之城 35张
     * $dt=>17    2021-02-17   会员解锁 40张
     * @throws \Exception
     */
    public function getCoupon()
    {
        $year = input('year/d', 0);
        $dt = input('dt/d', 0);

        $dateArr = $this->activeConfig[$year]['code'];

        if (!$dt || !isset($dateArr[$dt]))
        {
            return show(config('code.error'), '活动暂未开始');
        }

        $time = Util::testGetTime((string)$year);

        if ($time > $dateArr[$dt]['end_date'])
        {
            return show(config('code.error'), '活动已结束');
        }
        if ($time < $dateArr[$dt]['date'])
        {
            return show(config('code.error'), '活动暂未开始');
        }
        // 获取redis操作对象
        $redis = CacheManage::getInstance()->redisHandler;
        // 获取领取过优惠券的用户
        $giveData = $redis->lRange('year' . $year . ':activ_send_uid:' . $dateArr[$dt]['group_id'], 0, -1);
        if (in_array($this->user['id'], $giveData, false))
        {
            return show(config('code.error'), '已经领过了～');
        }
        // 缓存KEY
        $cacheKey = 'year' . $year . ':activ:' . $dateArr[$dt]['group_id'];
        // 获取优惠券剩余数量
        $couponNum = $redis->lLen($cacheKey);
        if ($couponNum)
        {
            $code = $redis->lPop($cacheKey);
            if ($code)
            { // 抢到了优惠券
                $couponCodeModel = new CouponCode();
                $res = $couponCodeModel->codeGet($this->user['id'], $code);
                // 记录领取用户UID
                $redis->lPush('year' . $year . ':activ_send_uid:' . $dateArr[$dt]['group_id'], $this->user['id']);
                // 更新领取数量
                $redis->hIncrBy('year' . $year . ':activ_send_num', $dateArr[$dt]['group_id'], 1);
                if ($res)
                {
                    $this->giveRecordCacheAdd($year, $this->user, $dateArr[$dt]['group_id'], 2);
                    return show(config('code.success'), '已存放至"我的-卡券中心"');
                }

                return show(config('code.error'), '哎呀、已经抢没了～');
            }
        }

        return show(config('code.error'), '哎呀、已经抢没了～');
    }

    /**
     * 领取活动优惠券
     * @return Json
     * @throws Exception
     * @throws PDOException
     */
    public function getActivCoupon(): ?Json
    {
        $year = input('year/d', 0);
        $dt = input('dt/d', 0);

        $arr = $this->activeConfig[$year]['active'];

        if (!$dt && !isset($arr[$dt]))
        {
            return show(config('code.error'), '活动暂未开始');
        }

        $couponActiveModel = new ZlCouponActive();

        $res = $couponActiveModel->couponActivMoreGive($year, $this->user['id'], $arr[$dt]);

        if ($res)
        {
            $isOver = $couponActiveModel->isGiveOver ? 1 : 0;
            $this->giveRecordCacheAdd($year, $this->user, $arr[$dt], 1);
            return show(config('code.success'), '已存放至"我的-卡券中心"', ['is_over' => $isOver]);
        }

        return show(config('code.error'), $couponActiveModel->errorMsg);
    }

    /**
     * 记录领取记录
     * @param int $year
     * @param array $userinfo
     * @param int $id
     * @param int $type 1活动 2抢
     */
    private function giveRecordCacheAdd(int $year, array $userinfo, int $id, int $type = 1): void
    {
        $len = 15;
        // 获取redis操作对象
        $redis = CacheManage::getInstance()->redisHandler;

        $cacheKey = 'year' . $year . ':give:info';
        $num = $redis->lLen($cacheKey);

        if ($num >= $len)
        {
            $redis->rPop($cacheKey);
        }

        $info = [
            'nickname' => $userinfo['nickname'],
            'avatar' => $userinfo['avatar'],
            'id' => $id,
            'type' => $type,
        ];

        $record = \GuzzleHttp\json_encode($info, JSON_UNESCAPED_UNICODE);

        $redis->lPush($cacheKey, $record);
    }
}
